<template>
	<view>
		<view class="wanl-product">
			<!-- 
			<view class="product_warter" style="padding-top: unset;" :class="dataStyle"
				v-if="dataStyle == 'col-2-10' || dataStyle == 'col-2-15' || dataStyle == 'col-2-20' || dataStyle == 'col-2-25' || dataStyle == 'col-2-30'">
 -->
			<!-- 瀑布流布局 -->
			<view class="product_warter col-2-20 col-2-10 col-2-15" style="padding-top: unset;" v-if="water">
				<view class="wanl-waterfall">
					<view id="wanl-left-cloumn" class="wanl-cloumn">
						<view class="warter left" v-for="(item, index) in leftList" :key="index">
							<view>
								<!-- 首页-商品分类-活动-纵向 -->
								<block v-if="item == 'vertical'">
									<view class="product-activity" style="margin-bottom: 0;" @tap="toActivity(item)">
										<image :src="$wanlshop.oss(activity.img_url)" mode="widthFix"
											style="margin-bottom: 0;">
										</image>
									</view>
								</block>

								<view v-else @tap="handleGoods(item.id)">
									<view class="img-wrap">
										<view class="img-bg product-image"
											:style="{backgroundImage: 'url(' + $wanlshop.oss(item.image) + ')'}"></view>
									</view>
									<view class="content padding-bj">
										<view class="text-cut-2">
											<block v-if="dataType === 'groups'">
												<view class="cu-tag radius sm bg-red">
													{{ item.is_ladder === 1 ? '阶梯' : item.people_num + '人' }}拼团
												</view>
											</block>
											<text class="margin-left-xsd text-30 product-title">{{ item.title }}</text>
										</view>
										<view class="goods-tag">
										</view>
										<view class="flex align-center justify-between">
											<view class="flex align-center" style="gap: 20rpx;">
												<view class="text-red text-bold text-lg">
													<text class="text-price">{{ item.price }}</text>
												</view>
												<view class="text-sm wanl-gray"
													style="font-size: 20rpx; color: #9C9C9C;">
													销量<text class="text">{{ item.sales }}</text>
												</view>
											</view>

											<view class="text-sm wanl-gray" v-if="dataType === 'groups'">
												<text>已拼团 {{ $wanlshop.toFormat(item.groups_num, 'hundred') }} 件</text>
											</view>
											<view class="cart-icon" v-else>
												<!-- <text>{{$wanlshop.toFormat(item.comment, 'hundred')}} 评价</text> -->
												<image src="../../static/images/default/cart_icon.png" mode="widthFix">
												</image>
											</view>
										</view>
										<!-- 	<view class="cu-tag radius sm line-orange" v-if="1"
											style="width: 18.4vw;height: 4vw; display: block;text-align: center;">金牌猫粮首选
										</view> -->
									</view>
								</view>
							</view>
						</view>
					</view>
					<view id="wanl-right-cloumn" class="wanl-cloumn">
						<view class="warter right" v-for="(item, index) in rightList" :key="index"
							@tap="handleGoods(item.id)">

							<view class="img-wrap">
								<view class="img-bg product-image"
									:style="{backgroundImage: 'url(' + $wanlshop.oss(item.image) + ')'}"></view>
							</view>

							<view class="content padding-bj">
								<view class="text-cut-2">
									<block v-if="dataType === 'groups'">
										<view class="cu-tag radius sm bg-red">
											{{ item.is_ladder === 1 ? '阶梯' : item.people_num + '人' }}拼团
										</view>
									</block>
									<text class="margin-left-xsd text-24 product-title">{{ item.title }}</text>
								</view>
								<view class="goods-tag">
								</view>
								<view class="flex align-center justify-between">
									<view class="flex align-center" style="gap: 20rpx;">
										<view class="text-red text-bold text-lg">
											<text class="text-price">{{ item.price }}</text>
										</view>
										<view class="text-sm wanl-gray" style="font-size: 20rpx; color: #9C9C9C;">
											销量<text class="text">{{ item.sales }}</text>
										</view>
									</view>

									<view class="text-sm wanl-gray" v-if="dataType === 'groups'">
										<text>已拼团 {{ $wanlshop.toFormat(item.groups_num, 'hundred') }} 件</text>
									</view>
									<view class="cart-icon" v-else>
										<!-- <text>{{$wanlshop.toFormat(item.comment, 'hundred')}} 评价</text> -->
										<image src="../../static/images/default/cart_icon.png" mode="widthFix"></image>
									</view>
								</view>
								<!-- <view class="cu-tag radius sm line-orange" v-if="1"
									style="width: 18.4vw;height: 4vw; display: block;text-align: center;">猫咪驱虫专家</view> -->
							</view>

						</view>
					</view>
				</view>
			</view>

			<!-- 普通布局 -->
			<view v-else>
				<!-- 首页-商品分类-活动-横向 -->
				<view class="product-activity" v-if="activity.img_url" style="margin: 0 20rpx 20rpx;" @tap="toActivity(activity)">
					<!-- <view class="img-bg" :style="{ background: `url(${$wanlshop.oss(activity.img_url)})` }">
					</view> -->
					<image :src="$wanlshop.oss(activity.img_url)" mode="widthFix"></image>
				</view>

				<view class="product_list col-2-20 col-2-10 col-2-15">
					<view class="item" v-for="(item, index) in dataList" :key="index" @tap="handleGoods(item.id)">
						<view class="img-bg normal-img" :style="{ background: `url(${$wanlshop.oss(item.image)})` }">
						</view>
						<view class="content padding-bj align-start" style="height: fit-content;">
							<view class="text-cut-2">
								<block v-if="dataType === 'groups'">
									<view class="cu-tag radius sm bg-red">
										{{ item.is_ladder === 1 ? '阶梯' : item.people_num + '人' }}拼团
									</view>
								</block>
								<text class="margin-bottom-sm text-30 product-title">{{ item.title }}</text>
							</view>

							<view class="flex align-center justify-between">
								<view class="flex align-center" style="gap: 20rpx;">
									<view class="text-red text-bold text-lg">
										<text class="text-price">{{ item.price }}</text>
									</view>
									<view class="text-sm wanl-gray" style="font-size: 20rpx; color: #9C9C9C;">
										销量<text class="text">{{ item.sales }}</text>
									</view>
								</view>

								<view class="text-sm wanl-gray" v-if="dataType === 'groups'">
									<text>已拼团 {{ $wanlshop.toFormat(item.groups_num, 'hundred') }} 件</text>
								</view>
								<view class="cart-icon" v-else>
									<image src="../../static/images/default/cart_icon.png" mode="widthFix"></image>
								</view>
							</view>
						</view>
					</view>
				</view>

			</view>
		</view>
	</view>
</template>

<script>
	/**
	 * wanlProduct 商品
	 * @description 商品组件 深圳前海万联科技有限公司 https://www.wanlshop.com（除万联官方内嵌系统，未经授权严禁使用）
	 * @著作权：WanlShop 登记号：2020SR0255711 版本：V1.0.0
	 * @property {Array} dataList 列表数据
	 * @property {String} dataStyle 列表样式
	 * @example <wanl-product />
	 */
	export default {
		name: 'wanlProduct',
		props: {
			activity: {
				type: Object,
				default: function() {
					return {
						img_url: "",
						target_url: "",
						column: ""
					};
				}
			},
			dataList: {
				type: Array,
				required: true,
				default: function() {
					return [];
				}
			},
			dataType: {
				type: String,
				default: 'goods'
			},
			water: {
				type: Boolean,
				default: true
			}
		},
		data() {
			return {
				//addTime: 180,
				addTime: 0,
				leftList: [],
				rightList: [],
				tempList: [],
				children: []
			}
		},
		watch: {
			copyFlowList(nVal, oVal) {
				// 取差值，即这一次数组变化新增的部分
				let startIndex = Array.isArray(oVal) && oVal.length > 0 ? oVal.length : 0;
				if (nVal.slice(startIndex).length == 0) {
					this.leftList = [];
					this.rightList = [];
					this.tempList = this.cloneData(this.copyFlowList);
				} else {
					this.tempList = this.tempList.concat(this.cloneData(nVal.slice(startIndex)));
				}
				this.splitData();
			},
		},
		mounted() {
			this.tempList = this.cloneData(this.copyFlowList);
			this.splitData();
		},
		computed: {
			// 破坏flowList变量的引用，否则watch的结果新旧值是一样的
			copyFlowList() {
				return this.cloneData(this.dataList.reverse());
			},
			// 活动图方向
			column() {
				return this.activity ? this.activity.column : '';
			}
		},
		methods: {
			// 前往活动页
			toActivity(item) {
				this.$api.post({
					loadingTip: '加载中',
					url: `/wanlshop/activity/detail`,
					data: {
						type: 'category',
						type_id: item.category_id
					},
					success: result => {
						uni.navigateTo({
							url: `/pages/page/activityPage`,
							success: (res) => {
								res.eventChannel.emit('data', {
									activity: result?.title,
									productList: result?.categories || [],
									headerImage: result?.header_img,
									footerImage: result?.footer_img,
								})
							}
						})
					}
				})
			},
			async splitData() {
				if (!this.tempList.length) return;

				let rightRect = await this.getRect('#wanl-right-cloumn');
				let leftRect = await this.getRect('#wanl-left-cloumn');
				// 如果左边小于或等于右边，就添加到左边，否则添加到右边
				let item = this.tempList[0];
				if (!item) return;
				item.image = this.$wanlshop.oss(item.image, 172, 0, 1);
				item.comment = this.$wanlshop.toFormat(item.comment, 'hundred');
				item.praise = item.comment > 0 ? parseInt((item.praise / item.comment) * 100) : 0;

				// 插入活动卡片
				if (this.column == 'vertical' && this.leftList.length == 0) {
					this.leftList.push('vertical')
				}

				if (leftRect.height < rightRect.height) {
					this.leftList.push(item);
				} else if (leftRect.height > rightRect.height) {
					this.rightList.push(item);
				} else {
					// 这里是为了保证第一和第二张添加时，左右都能有内容
					// 因为添加第一张，实际队列的高度可能还是0，这时需要根据队列元素长度判断下一个该放哪边
					if (this.leftList.length <= this.rightList.length) {
						this.leftList.push(item);
					} else {
						this.rightList.push(item);
					}
				}
				// 移除临时列表的第一项
				this.tempList.splice(0, 1);
				// 如果临时数组还有数据，继续循环
				if (this.tempList.length) {
					setTimeout(() => {
						this.splitData();
					}, this.addTime)
				}
			},
			// 复制而不是引用对象和数组
			cloneData(data) {
				return JSON.parse(JSON.stringify(data));
			},
			getRect(selector, all) {
				return new Promise(resolve => {
					let query = null;
					// 支付宝小程序不能加后面的.in(this)，是它自身的限制
					// #ifndef MP-ALIPAY
					query = uni.createSelectorQuery().in(this)
					// #endif
					// #ifdef MP-ALIPAY
					query = uni.createSelectorQuery()
					// #endif
					//setTimeout(() => {
						query[all ? 'selectAll' : 'select'](selector)
							.boundingClientRect(rect => {
								if (all && Array.isArray(rect) && rect.length) {
									resolve(rect)
								}
								if (!all && rect) {
									resolve(rect)
								}
							})
							.exec()
					//},0)
				})
			},
			handleGoods(id) {
				if (this.dataType === 'goods') {
					this.onGoods(id);
				} else if (this.dataType === 'groups') {
					this.$wanlshop.to(`/pages/apps/groups/goods?id=${id}`);
				}
			}
		}
	};
</script>

<style lang="scss" scoped>
	.wanl-product {
		background-color: transparent;
		
		
	}


	/* 瀑布流布局 */
	.wanl-waterfall {
		display: flex;
		flex-direction: row;
		align-items: flex-start;

		.wanl-cloumn {
			display: flex;
			flex: 1;
			flex-direction: column;
			height: auto;
			width: 50%;

			.wanl-image {
				width: 100%;
			}

			.product-image {
				width: 100%;
				min-height: 340rpx;
				background-size: cover !important;
				background-position: center !important;
			}

			.warter {
				border: 2rpx solid #dfdfdf;
			}
		}
	}

	.content {
		padding: 24rpx 16rpx;

		.cart-icon {
			width: 44rpx;
			height: 44rpx;

			image {
				width: 100%;
				display: block;
			}
		}
	}

	.product-title {
		display: block;
		width: 100%;
		font-size: 26rpx;
		font-weight: bold;
		overflow: hidden;
		white-space: nowrap;
	}

	.product-activity {
		border-radius: 20rpx;
		overflow: hidden;
		box-sizing: border-box;
		image {
			width: 100%;
			display: block !important;
		}
	}

	.image {
		display: block !important;
	}

	/* 普通布局 */
	.wanl-product .product_list.col-2-20 {
		padding-top: 0;

		.item {
			border: 2rpx solid #dfdfdf;
		}
	}

	.normal-img {
		width: 100%;
		height: 340rpx !important;
		background-size: cover !important;
		background-position: center !important;
	}
</style>